package cre.sample.test.classloader;

import java.lang.reflect.Method;

public class ClassIdentity {

	public static void main(String[] args) {
		new ClassIdentity().testClassIdentity();
	}

	public void testClassIdentity() {
		//为了演示不同类加载器加载同一个类，得到的是不同的类，这里的Sample类不能在当前CLASSPATH下，不然
		//会被System Classloader先加载，根据双亲委派模式，自定义的类加载器会首先委派给父类System Classloader，
		//从而得到已经加载过的Sample类的实例
		String classDataRootPath = "C:\\Users\\CreGu\\git\\cre-parent\\cre-sample\\classdata";
		FileSystemClassLoader fscl1 = new FileSystemClassLoader(classDataRootPath);
		FileSystemClassLoader fscl2 = new FileSystemClassLoader(classDataRootPath);
		String className = "cre.sample.test.classloader.Sample";
		try {
			Class.forName(className, true,ClassLoader.getSystemClassLoader());
			Class.forName(className, true, fscl1);
			
			Class<?> class1 = fscl1.loadClass(className);
			Object obj1 = class1.newInstance();
			
			Class<?> class2 = fscl2.loadClass(className);
			Object obj2 = class2.newInstance();
			Method setSampleMethod = class1.getMethod("setSample", java.lang.Object.class);
			setSampleMethod.invoke(obj1, obj2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
